package com.pine.common.captcha;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.CodeGenerator;
import com.pine.common.captcha.config.CaptchaCodeProperties;
import com.pine.common.captcha.config.CaptchaProperties;
import com.pine.common.captcha.core.CaptchaCodeInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.awt.*;

/**
 * <p>
 * 验证码client
 * </p>
 *
 * @author pine manage
 * @since 2024-08-21
 */
@Component
public class CaptchaClient {
    @Resource
    private CodeGenerator codeGenerator;

    @Resource
    private Font font;
    @Resource
    private CaptchaProperties captchaProperties;
    @Resource
    private CaptchaCodeProperties captchaCodeProperties;


    /**
     * 获取验证码
     */
    public CaptchaCodeInfo getCaptchaCode() {
        AbstractCaptcha captcha = generateCaptcha();
        captcha.setGenerator(codeGenerator);
        captcha.setTextAlpha(captchaProperties.getTextAlpha());
        captcha.setFont(font);

        // 返回结果
        String captchaCode = captcha.getCode();
        String imageBase64Data = captcha.getImageBase64Data();
        return new CaptchaCodeInfo(captchaCode, imageBase64Data, captchaProperties.getExpireSeconds());
    }

    /**
     * 验证验证码
     *
     * @param userInputCaptchaCode 用户输入的验证码
     * @param captchaCode          验证码
     */
    public boolean verifyCaptchaCode(String captchaCode, String userInputCaptchaCode) {
        return codeGenerator.verify(captchaCode, userInputCaptchaCode);
    }

    private AbstractCaptcha generateCaptcha() {
        int width = captchaProperties.getWidth();
        int height = captchaProperties.getHeight();
        int interfereCount = captchaProperties.getInterfereCount();
        int codeLength = captchaCodeProperties.getLength();

        return switch (captchaProperties.getType()) {
            case GIF -> CaptchaUtil.createGifCaptcha(width, height, codeLength);
            case LINE -> CaptchaUtil.createLineCaptcha(width, height, codeLength, interfereCount);
            case SHEAR -> CaptchaUtil.createShearCaptcha(width, height, codeLength, interfereCount);
            case CIRCLE -> CaptchaUtil.createCircleCaptcha(width, height, codeLength, interfereCount);
            default -> throw new RuntimeException("不支持的验证码类型");
        };
    }
}
